const app = getApp()
import { Config } from '../../utils/config.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    path: 'pages/index/index'
  },

  showLoading: function () {
    var that = this;
    this.setData({
      showLoading: true
    })
  },
  hideLoading: function () {
    var that = this;
    this.setData({
      showLoading: false
    })
  },
  /**
   * 获取用户信息接口后的处理逻辑
   */
  getUserInfo: function (e) {
    var that = this;
    wx.login({
      success: function (res) {
        wx.getUserInfo({
          'withCredentials': true,
          success: data => {
            console.log(data);
            let rawData = data.rawData;
            let signature = data.signature;
            let encryptedData = data.encryptedData;
            let iv = data.iv;
            wx.request({
              url: Config.restUrl + 'mini/login',
              header: {
                'content-type': 'application/json',
              },
              data: {
                "rawData": rawData,
                "signature": signature,
                "iv": iv,
                "encryptedData": encryptedData,
                "code": res.code
              },
              method: 'POST',
              success: function (res) {
                if (res.data.code == 1) {
                  that.hideLoading()
                  wx.setStorageSync('token', res.data.data);
                  if (that.data.path == 'pages/home/home'){
                    wx.switchTab({
                      url: '/' + that.data.path
                    })
                  }else{
                    wx.navigateTo({
                      url: '/' + that.data.path
                    })
                  }
                } else {
                  wx.navigateTo({
                    url: '/pages/error/error'
                  })
                }
              }
            })
          },
          fail: function () {
            console.log("用户拒绝了授权");
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.path) {
      this.data.path = options.path;
    } else {
      this.data.path = 'pages/home/home';
    }
    // 在没有 open-type=getUserInfo 版本的兼容处理
    if (!this.data.canIUse) {
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          wx.navigateTo({
            url: '/' + this.data.path
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})